<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="rule-form">
        <el-form-item label="设备名称" prop="equipmentAccountId">
          <el-input disabled v-model="ruleForm.equipmentAccountId" />
        </el-form-item>

        <el-form-item label="故障类型" prop="faultType">
          <el-select v-model="ruleForm.faultType" multiple placeholder="请选择故障类型">
            <el-option v-for="item in DictionaryList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="故障等级" prop="faultLevel">
          <el-select v-model="ruleForm.faultLevel" filterable placeholder="请选择故障等级">
            <el-option v-for="(item, i) in ['紧急', '严重', '一般']" :key="i" :label="item" :value="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="故障描述" prop="faultDescribe">
          <el-input type="textarea" placeholder="请输入故障描述" v-model="ruleForm.faultDescribe" maxlength="50"
            show-word-limit />
        </el-form-item>

        <el-divider>附件：异常图片/异常视频</el-divider>

        <el-form-item label="故障图片">
          <Image-upload :value='ruleForm.repairImages' @input="handleInput" />
        </el-form-item>

        <el-form-item label="故障视频">
          <Video-upload ref="videoUpload" v-model="ruleForm.faultVideo" @returnBack="handleReturnBack" />
        </el-form-item>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div class="dialog_footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listEquipmentAccount, listDictionary, listDetail, updateCreate } from '@/api/maintenance/management/equipmentAssembly.js'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  sourceId: '',// 维修id
  faultType: [], //故障类型
  faultDescribe: "", //故障描述
  faultLevel: '',//故障等级（0紧急 1严重 2一般）
  repairImages: [], //图片集合
  faultVideo: "" //视频
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
function processRuleForm (ruleForm) {
  const data = Object.assign({}, ruleForm)
  delete data.equipmentAccountId
  const images = ruleForm.repairImages.map(item => {
    if (item.url) {
      return {
        image: item.url
      }
    } else {
      return {
        image: item
      }
    }

  })
  const str = ruleForm.faultType.join(',')
  data.faultType = str
  data.repairImages = images
  return data
}

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '维修工单',
      DictionaryList: [],
      equipmentAccountList: [],//设备名称接收数组
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        equipmentAccountId: [
          { required: true, message: '请选择设备', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultType: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        repairImages: [
          { required: true, message: '请上传故障图片', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultLevel: [
          { required: true, message: '请选择故障等级', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultDescribe: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  methods: {
    // 设备名称和异常项目数据接口---------------------------------------------
    async handleListType () {
      const { data: res1 } = await listEquipmentAccount({ 'params[userStatuses]': '0,1,2,4', 'params[statuses]': '0,3' })//设备名称
      const { data: res2 } = await listDictionary({ dictType: 'fault_type', status: 0 })//异常项目，字典单位
      this.equipmentAccountList = res1
      this.DictionaryList = res2
    },
    // 上传图片处理方法-----------------
    handleInput (val) {
      this.ruleForm.repairImages = val
    },
    // 上传视频处理方法--------------------
    handleReturnBack (val) {
      this.ruleForm.faultVideo = val
    },
    // 打开表单对话框
    openDialog (id = null) {
      this.handleListType()
      if (id) {
        listDetail(id).then(async res => {
          this.isUpdateForm = true
          this.dialogTitle = '转维修工单'
          /** 修改时的表单参数赋值 --------------------------------------------------------------------------------------------------------------------- */
          // -----------------------------------------已消除展示的数据 -------------------------------------
          this.$set(this.ruleForm, 'equipmentAccountId', res.data.eaPartInfoVo.equipmentName + '（' + res.data.eaPartInfoVo.equipmentName + '）')
          this.ruleForm.sourceId = res.data.equipmentRepairId
          const { data: res2 } = await listDictionary({ dictType: 'abnormal_project', status: 0 })//异常项目，字典单位
          this.equipmentAccountTitle = res.data.eaPartInfoVo.equipmentNum
          // this.ruleForm.faultType = 
          let arr = []
          res.data.abnormalProject.split(',').map(item => {
            res2.map(i => {
              if (item == i.dictValue) {
                arr.push(i.dictLabel)
              }
            })
          })

          this.ruleForm.faultDescribe = res.data.describe + arr.join(',')
          this.ruleForm.repairImages = res.data.equipmentRepairImages.map(item => item.image)
          this.ruleForm.faultVideo = res.data.video
          this.dialogVisible = true
        })
      }
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        const data = processRuleForm(this.ruleForm)
        if (valid) {
          if (this.ruleForm.repairImages.length || this.ruleForm.faultVideo) {
            updateCreate(data).then((res) => {
              this.$message({
                message: '转维修单成功',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          } else {
            this.$message({
              message: '请上传故障图片或者故障视频！',
              type: 'error'
            })
          }
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      // this.ruleForm = Object.assign({}, ruleForm)
      this.$nextTick(function () {
        this.$refs['ruleForm'].clearValidate()
      });
      this.dialogVisible = false
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 500px;
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}
</style>
